/// <reference path="./Eventable.ts" />

namespace tetris {
    export enum ByWhat {
        NONE = 0x00,
        MANUAL = 0x01,
        CODE = 0x02,
        ALL = 0x03
    };

    export class StateManager extends Eventable {
        private _pause: ByWhat;
        private _over: boolean;

        constructor() {
            super();
            this._pause = ByWhat.NONE;
        }

        get isPaused() {
            return !!(this._pause & ByWhat.ALL);
        }

        get isPausedByManual() {
            return !!(this._pause & ByWhat.MANUAL);
        }

        get isRestartable() {
            return this.isPausedByManual || this.isOver;
        }

        get isOver() {
            return this._over
        }

        pause(byWhat) {
            const isPaused = this.isPaused;
            this._pause |= byWhat;
            if (!isPaused) {
                this.trigger("pause");
            }
        }

        resume(byWhat) {
            if (this.isOver) {
                return;
            }
            const isPaused = (this._pause &= ~byWhat) & ByWhat.ALL;
            if (!isPaused) {
                this.trigger("resume");
            }
        }

        restart() {
            this._over = false;
            this.trigger("restart");
            this.resume(ByWhat.ALL);
        }

        over() {
            this._over = true;
            this.pause(ByWhat.ALL);
        }
    }
}